package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dao.ICommonDao;

public abstract class CommonDao<T> implements ICommonDao<T> {

	@PersistenceContext
	protected EntityManager em;

	public abstract T find(int id);

	public T findByExample(T example) {
		try {
			return (T) em.createQuery(
					"select obj from T obj " + getWhereClause(example))
					.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

	public void persist(T obj) {
		em.persist(obj);
	}

	public void remove(T obj) {
		em.remove(obj);
	}

	public void removeByExample(T example) {
		try {
			em.createQuery("delete from T obj " + getWhereClause(example))
					.getSingleResult();
		} catch (Exception e) {

		}
	}

	public List<T> findAll() {
		try {
			return (List<T>) em.createQuery("select obj from T obj ")
					.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	public List<T> findAllByExample(T example) {
		try {
			return (List<T>) em.createQuery(
					"select obj from T obj " + getWhereClause(example))
					.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	public abstract String getWhereClause(T obj);

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

}